﻿using IPTools.Core;
using Microsoft.AspNetCore.Http;
using UAParser;
using YiShop.Framework.Constants;
using YiShop.System.Repositories;

namespace YiShop.System.Services
{
    /// <summary>
    ///  系统访问记录 Service
    ///  author ruoyi
    ///  date   2023-08-22 10:07:36
    /// </summary>
    public class SysLogininforService : ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly SysLoginInforRepository _sysLoginInforRepository;

        public SysLogininforService(IHttpContextAccessor httpContextAccessor, SysLoginInforRepository sysLoginInforRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _sysLoginInforRepository = sysLoginInforRepository;
        }

        /// <summary>
        /// 记录登录信息
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="status">状态</param>
        /// <param name="message">消息</param>
        public async Task AddAsync(string username, string status, string message)
        {
            var context = _httpContextAccessor.HttpContext;
            ClientInfo clientInfo = Parser.GetDefault().Parse(context.GetUserAgent());
            string? ip = context.Connection.RemoteIpAddress?.ToString();
            IpInfo location;
            if (ip == "127.0.0.1" || ip == "::1")
            {
                location = new IpInfo() { Province = "本地", City = "本机" };
            }
            else
            {
                location = IpTool.Search(ip);
            }
            // 封装对象
            SysLoginInfor logininfor = new SysLoginInfor();
            logininfor.UserName = username;
            logininfor.Ipaddr = ip;
            logininfor.LoginLocation = location.Province + "-" + location.City;
            logininfor.Browser = clientInfo.Device.Family;
            logininfor.Os = clientInfo.OS.Family;
            logininfor.Msg = message;
            logininfor.LoginTime = DateTime.Now;

            // 日志状态
            var statuses = new List<string> { GlobalConstants.LOGIN_SUCCESS, GlobalConstants.LOGOUT, GlobalConstants.REGISTER };
            if (statuses.Contains(status))
            {
                logininfor.Status = Status.Enabled;
            }
            else if (GlobalConstants.LOGIN_FAIL.Equals(status))
            {
                logininfor.Status = Status.Disabled;
            }
            // 插入数据
            await _sysLoginInforRepository.InsertAsync(logininfor);

        }
    }
}
